/* eslint-disable no-unused-vars */
<template>
  <div>
    <common-head :title="$route.name" />
    <div class="wrap">
      <van-address-list
        v-model="chosenAddressId"
        :list="contactLists"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="choseContact"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchContacts } from '@api'

export default {
  components: { CommonHead },
  name: 'AddressLists',
  data () {
    return {
      contacts: [],
      chosenAddressId: '-1',
      from: ''
    }
  },
  created () {
    this.fetchContacts()
  },
  beforeRouteEnter (to, from, next) {
    // 判断是否从订单页进入收货地址列表
    /*
      订单页进来，切换 跳会订单页 同时，将选中的收货地址id传递获取
    */
    next(ins => {
      // 标记 我从哪个路由过来的
      ins.from = from.path
    })
  },
  methods: {
    choseContact (contact, index) {
      // 点击切换联系人
      /*
        判断 this.from 如果值 是 /orderCreate 从订单页过来的
      */
      if (this.from === '/orderCreate') {
        this.$router.replace({
          path: '/orderCreate',
          query: {
            contactId: contact.id
          }
        })
      }
    },
    initChoseId () {
      /*
      默认选中收货人id
      1 判断是否有默认联系人 默认联系人 id
      2 没有 第一个收货地址id
      */
      // 联系人为空
      if (this.contacts.length === 0) {
        return false
      }
      const defaultContact = this.contacts.find((contact) => contact.isDefault)
      if (defaultContact) {
        // 有默认联系人
        this.chosenAddressId = defaultContact.id
      } else {
        this.chosenAddressId = this.contacts[0].id
      }
    },
    onAdd () {
      this.$router.push('/addressAdd')
    },
    onEdit ({ id }) {
      // 调到到修改联系人 传id
      this.$router.push({
        path: '/addressUpdate',
        query: {
          id
        }
      })
    },
    fetchContacts () {
      // 获取收货地址列表
      fetchContacts({
        token: this.getToken()
      }).then((res) => {
        if (res.data.code === 0) {
          this.contacts = res.data.data.result
          // 调用初始化选中收货地址id
          this.initChoseId()
        }
      })
    }
  },
  computed: {
    contactLists () {
      const lists = []
      this.contacts.forEach((contact) => {
        const _contact = {}
        for (const key in contact) {
          if (key === 'linkMan') {
            _contact.name = contact[key]
          } else if (key === 'mobile') {
            _contact.tel = contact[key]
          } else {
            _contact[key] = contact[key]
          }
        }
        lists.push(_contact)
      })
      return lists
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  padding-top: 46px;
}
</style>
